from lib.settings import BTCTRADE_API_URL
import hashlib
import urllib.request
import time
import urllib
import hmac
import urllib.parse
import json

'''
获取市场深度
'''
def getDepth():
    response = urllib.request.urlopen(BTCTRADE_API_URL['host'] + BTCTRADE_API_URL['depth'], timeout=1)
    if response.status == 200:
        mybytes = response.read()
        mystr = mybytes.decode("utf8")
        response.close()
        return json.loads(mystr)
    else:
        response.close()
        return False


# send requests
def request(method, params, apikey, secretkey):
    Od = {}
    Od['key'] = apikey
    Od['nonce'] = int(time.time() * 1000000)
    Od['version'] = 2

    for key in params:
        Od[key] = params[key]

    Od['signature'] = signature(Od, secretkey)
    response = urllib.request.urlopen(BTCTRADE_API_URL['host'] + method, urllib.parse.urlencode(Od).encode('utf-8'))
    if response.status == 200:
        mybytes = response.read()
        mystr = mybytes.decode("utf-8")
        response.close()
        return json.loads(mystr)
    else:
        response.close()
        return False


# create signature
def signature(params, secretkey):
    payload = urllib.parse.urlencode(params)
    md5prikey = hashlib.md5(secretkey.encode('utf-8')).hexdigest()

    # 加了个parse：因为python3
    sign = urllib.parse.quote(hmac.new(md5prikey.encode('utf-8'), payload.encode('utf-8'), digestmod=hashlib.sha256).hexdigest())
    return sign


'''
给深度排序
'''
def sort_and_format(l, reverse=False):
    l.sort(key=lambda x: float(x[0]), reverse=reverse)
    r = []
    for i in l:
        r.append({'price': float(i[0]), 'volume': float(i[1])})
    return r

